﻿using Common.Device.Enums;
using Common.Device.Models;
using Common.Device.ViewModels;
using Common.Tool;
using Common.Tool.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static Common.Device.Enums.TestEnum;
using static MaterialDesignThemes.Wpf.Theme;

namespace Common.Device.Views
{
    /// <summary>
    /// DeviceOrderView.xaml 的交互逻辑
    /// </summary>
    public partial class TestListView : UserControl
    {
        //todo 拖拽
        public ViewModels.TestListViewModel viewModel = new ViewModels.TestListViewModel();
        public TestListView()
        {
            InitializeComponent();
            DataContext = viewModel;
            InitTimer();
        }
        private void OrderList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (viewModel.StartState == TestEnum.StartState.停止) { return; }
            //双击解析测试项，拖拽干扰已屏蔽
            //var order = Dialogs.OrderEditView.Show(OrderList.SelectedIndex == -1 ? null : viewModel.Orders[OrderList.SelectedIndex]);
            //if (order != null)
            //{
            //    order.index = viewModel.Orders.Count + 1;
            //    viewModel.Orders.Add(order);
            //}
        }
        /// <summary>
        /// 新增测试项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InsOrder(object sender, RoutedEventArgs e)
        {
            if (viewModel.StartState == TestEnum.StartState.停止) { return; }
            //弹出编辑界面
            var order = Dialogs.OrderEditView.Show(null);
            if (order != null)
            {
                order.index = viewModel.Orders.Count + 1;
                viewModel.Orders.Add(order);
            }
        }
        /// <summary>
        /// 查看修改测试项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditOrder(object sender, RoutedEventArgs e)
        {
            try
            {
                if (viewModel.StartState == TestEnum.StartState.停止) { return; }
                //弹出编辑界面
                var order = Dialogs.OrderEditView.Show(OrderList.SelectedIndex == -1 ? null : viewModel.Orders[OrderList.SelectedIndex]);
                if (order != null)
                {
                    var result = View.Controls.Dialogs.TipView.Show($"发现已选择测试项[{order.index}] {order.name}?\r\n请确认后点击!", new Dictionary<string, Brush> { { "修改", View.Base.Colors.PrimaryColor }, { "新增", View.Base.Colors.SuccessColor }, { "取消", View.Base.Colors.DangerColor } });
                    if (result == "修改")
                    {
                        order.index = viewModel.Orders[OrderList.SelectedIndex].index;
                        viewModel.Orders[OrderList.SelectedIndex] = order;
                    }
                    if (result == "新增")
                    {
                        order.index = viewModel.Orders.Count + 1;
                        viewModel.Orders.Add(order);
                    }
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error(ex.Message);
            }
        }
        /// <summary>
        /// 输出测试项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelOrder(object sender, RoutedEventArgs e)
        {
            if (viewModel.StartState == TestEnum.StartState.停止) { return; }
            if (OrderList.SelectedIndex == -1)
                return;
            viewModel.Del(viewModel.Orders[OrderList.SelectedIndex]);

        }
        #region 拖拽
        System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
        ListViewItem selectItem = null;
        int timeOut = 0;
        private void InitTimer()
        {
            try
            {
                //拖拽按下计时
                timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
                timer.Tick += new EventHandler(timer_Tick);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                //按下计时等于4次
                if (++timeOut == 4)
                {
                    // 获取被拖拽的项
                    draggedItem = OrderList.ItemContainerGenerator.ItemFromContainer(selectItem);

                    // 开始拖拽操作
                    DragDrop.DoDragDrop(selectItem, draggedItem, DragDropEffects.Move);
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error(ex.Message);
            }

        }
        private object draggedItem;
        private void ListView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (viewModel.StartState == TestEnum.StartState.停止) { return; }
            var listView = sender as System.Windows.Controls.ListView;
            // 获取鼠标点击的列表项
            var hitTestResult = VisualTreeHelper.HitTest(listView, e.GetPosition(listView));
            var listViewItem = FindVisualParent<ListViewItem>(hitTestResult.VisualHit);

            if (listViewItem != null)
            {
                //鼠标按下清空时间
                timeOut = 0;
                //选中项
                selectItem = listViewItem;
                //计时
                timer.Start();
            }
        }
        private void ListView_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            timeOut = 0;
            timer.Stop();
        }
        private void ListView_DragEnter(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(TestOrder)))
            {
                e.Effects = DragDropEffects.None;
            }
        }
        private void ListView_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(TestOrder)))
            {
                var listView = sender as System.Windows.Controls.ListView;
                // 获取目标列表项
                var hitTestResult = VisualTreeHelper.HitTest(listView, e.GetPosition(listView));
                var targetListViewItem = FindVisualParent<ListViewItem>(hitTestResult.VisualHit);

                if (targetListViewItem != null)
                {
                    // 获取目标项的索引
                    int targetIndex = listView.ItemContainerGenerator.IndexFromContainer(targetListViewItem);

                    // 获取数据源
                    var items = (ObservableCollection<TestOrder>)listView.ItemsSource;

                    // 移除被拖拽的项
                    items.Remove((TestOrder)draggedItem);

                    // 在目标位置插入被拖拽的项
                    items.Insert(targetIndex, (TestOrder)draggedItem);
                    for (int i = 0; i < items.Count; i++)
                    {
                        items[i].index = i + 1;
                    }
                    // 刷新列表视图
                    listView.Items.Refresh();
                }
            }
        }
        private static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            var parentObject = VisualTreeHelper.GetParent(child);
            if (parentObject == null) return null;
            if (parentObject is T parent)
            {
                return parent;
            }
            return FindVisualParent<T>(parentObject);
        }
        #endregion

    }
}
